#!/bin/bash
param_count=$#

sounds_music="https://gitee.com/freecti/ippbx/attach_files/1699341/download"
            

function function_help {
    echo "FreeCTI IPPBX Command Line Tools"
    echo "Usage: $0 [command] [service]"
    echo "Commands:"
    echo "  setup: install and setup environment. Can only be executed once!"
    echo "  start: start containers"
    echo "  stop: stop containers"
    echo "  uninstall: Unmount the containers"
    echo "  shell: enter the container shell [web] [switch] [db] [core]"
    echo "  exec: excute the container command [web] [switch] [db] [core]"
}

function sounds_install {
    filename="zh.tar.gz"
    if [ ! -f $filename ];then
        wget -O $filename $sounds_music
        tar -xzvf $filename -C ./volumes/freeswitch/sounds/
    fi
}

function function_setup {
    stty erase '^H'
    echo -n "Are you sure want to install and set up environment?(Y/N):"
    read ANS
    if [[ "$ANS" =~ ^[Yy]$ ]]; then
        echo "Installing IPPBX ..."
    else
        echo "Aborting ..."
        exit 0
    fi

    # 输入ip地址
    while true; do
        stty erase '^H'
        echo -n "Please enter a valid IP address:"
        read  IP_ADDRESS
        #使用正则表达式检查SIP地址是否有效
        if [[ "$IP_ADDRESS" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
            echo "You entered the IP address: $IP_ADDRESS"
            echo
            break
        else
            echo "Invalid IP address. Please try again ..."
            echo
        fi
    done

    # 配置环境变量配置文件
    cp ./sample.env ./.env

    # 输入mysql用户名
    while true; do
        stty erase '^H'
        echo -n "Please enter your MySQL username (The default is freecti):"
        read username
        # 默认用户freecti
        if [ -z "$username" ];then
            username="freecti"
        fi
        # 用户名必须大于2个字符 小于10个字符
        if [ ${#username} -gt 2 ] && [ ${#username} -lt 10 ]; then
            echo "The username you entered is: $username"
            echo
            break
        else
            echo "Please re-enter your username ..."
            echo
        fi
    done

    # 修改.env文件中的mysql_user
    sed -i "s/^MYSQL_USER=.*/MYSQL_USER=$username/" ./.env

    # 设置mysql密码 字符超过6位
    while true; do
        stty erase '^H'
        echo -n "Please set a MySQL password (must be at least 6 characters long):"
        read -s mysql_passwd
        echo
        # 再次确认密码
        echo -n "Please confirm the MySQL password:"
        read -s mysql_passwd_confirm
        echo
        # 检查密码长度
        if [[ ${#mysql_passwd} -ge 6 ]]; then
            # 检查两次输入的密码是否一致
            if [[ "$mysql_passwd" == "$mysql_passwd_confirm" ]]; then
                echo "MySQL password has been set successfully ..."
                echo
                break
            else
                echo "Passwords do not match. Please try again ..."
                echo
            fi
        else
            echo "Password is too short. Please try again ..."
            echo
        fi
    done

    # 修改mysql .env文件内容
    sed -i "s/^MYSQL_ROOT_PASSWORD=.*/MYSQL_ROOT_PASSWORD=$mysql_passwd/" ./.env
    sed -i "s/^MYSQL_PASSWORD=.*/MYSQL_PASSWORD=$mysql_passwd/" ./.env
    sed -i "s/spring.datasource.username=.*$/spring.datasource.username=$username/" ./volumes/ippbx-core/application.properties
    sed -i "s/spring.datasource.password=.*$/spring.datasource.password=$mysql_passwd/" ./volumes/ippbx-core/application.properties

    # 检查 docker 是否安装
    echo "Checking docker ..."
    if ! command -v docker &> /dev/null; then
        echo "Docker is not installed. Install Docker ..."
        # 安装 docker 组件
        # curl -s https://get.docker.com | sh
        curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
        echo "Docker is installed ..."
    else
        echo "Docker is already installed ..."
    fi

    # 加载声音文件
    echo " Download the sound file ..."
    sounds_install

    #修改freeswtich的local.xml文件内容
    cp ./volumes/freeswitch/conf/local.xml.sample ./volumes/freeswitch/conf/local.xml
    sed -i "s/data=\"external_ip=[0-9.]\+\"/data=\"external_ip=$IP_ADDRESS\"/g" ./volumes/freeswitch/conf/local.xml
    chmod 777 volumes/freeswitch/conf/sip_profiles/gateways


    #初始化容器
    echo "Initializing containers ..."
    docker compose up -d


    #安装完成
    echo
    echo "The installation is complete....."
    echo "Please visit the website: http://$IP_ADDRESS"
}
            
# 启动 IPPBX
function function_start {
    echo "Start FreeCTI-IPPBX"
    docker compose start
}

# 停止 IPPBX
function function_stop {
    echo "Stop FreeCTI-IPPBX"
    docker compose stop
}

# 卸载 IPPBX
function function_uninstall {
    local answer
    # 确认是否删除IPPBX镜像文件
    stty erase '^H'
    echo "Are you sure you want to uninstall IPPBX? (Y/N)"
    read  answer
    if [[ "$answer" =~ ^[Yy]$ ]]; then
        echo "Uninstalling IPPBX ..."                    # 开始卸载过程
        docker compose down                              # 停止运行
        echo "Delete the docker image ... "
        docker rmi registry.cn-beijing.aliyuncs.com/freecti/ippbx-core:1.0.0 \
                   registry.cn-beijing.aliyuncs.com/freecti/ippbx-web:1.0 \
                   registry.cn-beijing.aliyuncs.com/freecti/mysql:8.3 \
                   registry.cn-beijing.aliyuncs.com/freecti/freeswitch:1.10.11       # 删除镜像 
        echo "The docker image is deleted ..."
        echo
    else
        echo "Skip deleting the PBX image ..."
        echo
    fi

    # 确认是否卸载卸载docker
    stty erase '^H'
    echo "Are you going to uninstall docker? (Y/N)"
    read answer
    if [[ "$answer" =~ ^[Yy]$ ]]; then
        echo "Uninstalling Docker ..."
        apt-get purge -y docker-ce docker-ce-cli containerd.io   # 卸载安装包
        sudo rm -rf /var/lib/docker                              # 删除数据目录
        sudo rm -rf /var/lib/containerd
        sudo rm -rf /etc/docker
        sudo rm -rf /run/docker
        sudo rm -rf /opt/containerd
        sudo apt  -y autoremove                                  # 清理依赖关系
        echo "docker uninstall successfully ..."
        echo
    else
        echo "Skipping Docker uninstallation ..."
        echo
    fi
    echo "The IPPBX was uninstalled successfully ..."
    echo
    exit 0

}

if [ $param_count -eq 0 ]; then
    function_help
    exit 0
fi

if [ "$1" == "help" ]; then
    function_help
elif [ "$1" == "setup" ]; then
    function_setup
elif [ "$1" == "start" ]; then
    function_start
elif [ "$1" == "stop" ]; then
    function_stop
elif [ "$1" == "uninstall" ];then
    function_uninstall
elif [ "$1" == "shell" ]; then
    docker exec -it ippbx-$2 /bin/bash
elif [ "$1" == "exec" ]; then
    docker exec -it ippbx-$2 $3 /bin/bash
else
    echo "Invalid parameter"]
fi